const util = require('../../utils/util.js');
var user = require('../../services/user.js');
const qiniuUploader = require("../../utils/qiniuUploader");
const Toast = require('../../utils/toast.js');

//创建录音控件
const recorderManager = wx.getRecorderManager()
//创建audio控件
const myaudio = wx.createInnerAudioContext()
var timer_j;
var timer_l;
var move_l = 0;

Page({
  data: {
    mainheight: '',
    recording: 0,
    j: 1, //帧动画初始图片
    isSpeaking: false, //是否正在说话
    last_time: '120', //倒计时时间
    is_show: true, //倒计时显示
    is_delete: false,
    showDanmu: true,
    showComment: false,
    quickreplyShow: false,
    socketopen: false,
    //音频列表
    lesson_res: [],
    playlessoninfo: {},
    commentlist: [], //弹幕信息列表
    roomNumber: '',
  },
  onLoad: function(e) {
    //console.log(e.id);
    this.getplaylessoninfo(e.id);
    var that = this;
    wx.getSystemInfo({
      success: function(res) {
        console.log(res)
        var mainheight = res.windowHeight * 2 - 152 - 76;
        that.setData({
          mainheight: mainheight
        })
      }
    })
    //creat socket
    this.creatsocket(e);

    //初始化七牛上传
    this.setqiniuoption();
  },
  //***页面卸载执行***
  onUnload: function() {
    wx.closeSocket()
  },
  creatsocket: function(e) {
    var that = this;
    wx.connectSocket({
      url: util.socketurl,
    })
    wx.onSocketOpen(function(res) {
      console.log('WebSocket连接已打开！')
      //set socket_status
      that.setData({
        socketopen: true
      })

      //update userinfo
      var userInfo = wx.getStorageSync('userInfo');
      var data = {
        type: 'addUser',
        broadcast: 1, //1：进行房间广播， 0不进行房间广播  //加入广播
        closebroadcast: 1, //1进行房间广播， 0不进行房间广播   //退出广播
        roomName: 'minichat_' + e.id,
        userId: userInfo.id,
        userName: userInfo.nickname,
        headUrl: userInfo.headurl,
        sendUser: userInfo,
      }
      //console.log(data)
      wx.sendSocketMessage({
        data: JSON.stringify(data)
      })
    })

    //监听socket收到消息
    wx.onSocketMessage(function(res) {
      //console.log('收到服务器内容：' + res.data)
      that.socketMessage(res.data);
    })

    //监听socket断开连接
    wx.onSocketClose(function(res) {
      that.setData({
        socketopen: false
      })
    })

  },
  getplaylessoninfo: function(lesson_id) { //获取课程信息
    let that = this;
    util.request('school/getplaylessoninfo', {
      lesson_id: lesson_id
    }, 'GET').then(function(res) {
      console.log(res.data);
      if (res.errno === 0) {
        that.setData({
          playlessoninfo: res.data.playlessoninfo,
        });
      }
    });
  },

  //音频播放  
  playAudio: function(e) {
    let that = this;
    let src = e.currentTarget.dataset.path;
    let key = e.currentTarget.dataset.key;
    console.log(e.currentTarget.dataset)
    let bl = e.currentTarget.dataset.bl;
    myaudio.autoplay = true;
    setTimeout(function() {
      myaudio.play();
    }.bind(that), 300)
    myaudio.src = src;
    //切换显示状态
    for (var i = 0; i < that.data.lesson_res.length; i++) {
      that.data.lesson_res[i].bl = false;
    }
    console.log('吞吞吐吐')
    console.log(that.data.lesson_res[key])
    that.data.lesson_res[key].bl = true;
    that.data.lesson_res[key].new = false;

    //开始监听
    myaudio.onPlay(() => {
      that.setData({
        lesson_res: that.data.lesson_res
      })
    })

    //结束监听
    myaudio.onEnded(() => {
      that.data.lesson_res[key].bl = false;
      that.setData({
        lesson_res: that.data.lesson_res
      })
    })
  },

  // 音频停止
  stoppAudio: function(e) {
    console.log('stop')
    let that = this;
    let src = e.currentTarget.dataset.path;
    let key = e.currentTarget.dataset.key;
    let bl = e.currentTarget.dataset.bl;
    //切换显示状态
    for (let i = 0; i < that.data.lesson_res.length; i++) {
      that.data.lesson_res[i].bl = false;
    }
    that.data.lesson_res[key].bl = false;

    myaudio.stop();
    //停止监听
    myaudio.onStop(() => {
      that.data.lesson_res[key].bl = false;
      that.setData({
        lesson_res: that.data.lesson_res
      })
    })
    //结束监听
    myaudio.onEnded(() => {
      that.data.lesson_res[key].bl = false;
      that.setData({
        lesson_res: that.data.lesson_res
      })
    })
  },
  //手指长按下开始录音
  touchdown: function() {
    let that = this
    console.log("手指按下了...")
    if (this.data.playlessoninfo.status != 1) {
      if (this.data.playlessoninfo.status == 0) {
        Toast('课程未开课！', 'fail', 1000);
      }
      if (this.data.playlessoninfo.status == 2) {
        Toast('课程已结束！', 'fail', 1000);
      }
      return false;
    }
    if (this.data.socketopen == false) {
      Toast('课程连接断开了！', 'fail', 1000);
      return false;
    }
    this.start();
    //this.audioStop();//如果在播放/停止播放
  },
  //手指抬起结束录音
  touchup: function() {
    console.log("手指抬起了...")
    if (this.data.isdelete == true) {
      this.speaking('stop');
      this.setData({
        isdelete: false,
      })
    } else {
      this.stop();
    }

  },
  //手指移动
  touchmove: function(e) {
    var that = this;
    console.log(e.touches[0].pageY);
    if (move_l == 0) {
      move_l = e.touches[0].pageY
    }
    if (move_l - e.touches[0].pageY >= 50) {
      that.setData({
        isdelete: true,
      })
    } else {
      that.setData({
        isdelete: false,
      })
    }
  },
  //开始录音的时候
  start: function() {
    myaudio.stop();
    var that = this;
    const options = {
      duration: 120000, //指定录音的时长，单位 ms
      sampleRate: 8000, //采样率
      numberOfChannels: 1, //录音通道数
      encodeBitRate: 16000, //编码码率
      format: 'aac', //音频格式，有效值 aac/mp3
    }
    //开始录音
    recorderManager.start(options);
    recorderManager.onStart(() => {
      console.log('recorder start')
      // //开始动画
      that.speaking('start');
    });
  },
  //停止录音
  stop: function() {
    let that = this
    recorderManager.stop();
    recorderManager.onStop((res) => {
      console.log(res)
      that.speaking('stop');
      console.log('停止录音', res.tempFilePath)
      if (parseFloat(res.duration / 1000) < 1) {
        Toast('录音时间不能少于1s', 'noicon');
        return;
      }
      var addtimestamp = Math.round(Date.now() / 1000);
      var size = `${parseFloat(res.duration / 1000).toFixed(1)}s`
      let arrInfo = {
        id: 0,
        res_type: 1, //1代表语音
        res_path: res.tempFilePath,
        size: size,
        upto: 1, //上传状态 0 代表未上传状态  // 或者上传失败 1 代表上传中 
      }
      var lesson_res = that.data.lesson_res;
      var key = lesson_res.length;
      lesson_res.push(arrInfo)
      //console.log(that.data.lesson_res)
      that.setData({
        lesson_res: lesson_res
      })
      //上传资源
      that.up_res(res.tempFilePath, key, size, addtimestamp, 1)

    })
  },
  //打开评论
  commentOpen: function() {
    this.setData({
      showComment: true
    })
  },
  //关闭评论
  closeComment: function() {
    this.setData({
      showComment: false
    })
  },
  //关闭弹幕
  danmuClose: function() {
    this.setData({
      showDanmu: false
    })
  },
  //开启弹幕
  danmuOpen: function() {
    this.setData({
      showDanmu: true
    })
  },
  //快捷回复
  quickreply: function() {
    this.setData({
      quickreplyShow: true
    })
  },
  closeQuickreply: function() {
    this.setData({
      quickreplyShow: false
    })
  },
  speaking: function(obj) {
    var that = this;
    if (obj == 'start') {
      that.setData({
        isSpeaking: true,
        recording: 1,
        last_time: 120,
      })
      var i = 1;
      var l = 120;
      timer_j = setInterval(function() {
        i++;
        if (i > 5) {
          i = 1
        }
        that.setData({
          j: i
        })
      }, 200);

      timer_l = setInterval(function() {
        l--;
        if (i > 5) {
          i = 1
        }
        that.setData({
          last_time: l
        })
      }, 1000);
    }

    if (obj == 'stop') {
      that.setData({
        isSpeaking: false,
        recording: 0
      })
      clearInterval(timer_j);
      clearInterval(timer_l);
    }


  },
  setqiniuoption: function() {
    let that = this;
    util.request('upload/getqiniutoken', 'GET').then(function(res) {
      //console.log(res.data);
      if (res.errno === 0) {
        //初始化七牛相关参数
        var options = {
          region: 'ECN', // 华东区
          //uptokenURL: util.apiurl+'upload/getqiniutoken',
          uptoken: res.data,
          domain: 'http://teachimg.178mr.com',
          shouldUseQiniuFileName: false
        };
        qiniuUploader.init(options);
      }
    });
  },
  up_res: function(path, key, size, addtimestamp, res_type) {
    console.log(res_type)
    let that = this;
    if (res_type == 1) {
      var up_key = 'sound/livesound/res' + Date.now() + '.aac'
    }
    if (res_type == 2) {
      var up_key = 'images/livesound/res' + Date.now()
    }

    //交给七牛上传  //先上传到七牛
    qiniuUploader.upload(path, (res) => {
        //上传成功后再上传到云服务器
        that.up_tosever(res.imageURL, key, size, addtimestamp, res_type)
      }, (error) => {
        console.error('error: ' + JSON.stringify(error));
      }, {
        region: 'ECN', // 华东区
        key: up_key
      },
      (progress) => {
        //console.log('上传进度', progress.progress)
        // console.log('已经上传的数据长度', progress.totalBytesSent)
        // console.log('预期需要上传的数据总长度', progress.totalBytesExpectedToSend)
      }, cancelTask => that.setData({
        cancelTask
      })
    );
  },
  up_tosever: function(res_path, key, size, addtimestamp, res_type) {
    let that = this;
    let data = {
      lesson_id: this.data.playlessoninfo.lesson_id,
      res_type: res_type,
      res_path: res_path,
      size: size,
      addtime: addtimestamp,
      lesson_teacher: this.data.playlessoninfo.lesson_teacher
    }

    //console.log(data);
    util.request('school/postlivelessonres', {
      addinfo: data
    }, 'POST').then(function(res) {
      console.log(res);
      if (res.errno === 0) {
        var lesson_res = that.data.lesson_res;
        console.log('up_tosever')
        lesson_res[key].upto = 2;
        lesson_res.forEach(item => {
          if (item.res_type === 1) {
            item.bl = false;
            item.new = true;
          }
        })
        that.setData({
          lesson_res: lesson_res
        });
        //发送soket消息
        var userInfo = wx.getStorageSync('userInfo');
        var data = {
          type: 'groupSend',
          roomName: 'minichat_' + that.data.playlessoninfo.lesson_id,
          sendUser: userInfo,
          sendMessage: {
            type: 'lesson_res',
            res_type: res_type,
            res_path: res_path,
            size: size,
            addtime: addtimestamp
          }
        }
        //console.log(data)
        wx.sendSocketMessage({
          data: JSON.stringify(data)
        })

      } else {


      }
    });
  },
  setlessonstatus: function(e) {
    var that = this;
    let status = e.currentTarget.dataset.status
    //改变课程状态
    util.request('school/setlessonstatus', {
      data: {
        status: e.currentTarget.dataset.status,
        lesson_id: this.data.playlessoninfo.lesson_id
      },
    }, 'POST').then(function(res) {
      console.log(res);
      if (res.errno === 0) {
        console.log(e)
        if (status == 1) {
          Toast('课程开课了！', 'success');
        }
        if (status == 2) {
          Toast('课程结束了！', 'success');
        }
        let playlessoninfo = that.data.playlessoninfo;
        playlessoninfo.status = e.currentTarget.dataset.status;
        that.setData({
          playlessoninfo: playlessoninfo
        })
      } else {

      }
    });

  },
  sendpic: function() {
    var that = this;
    if (this.data.playlessoninfo.status != 1) {
      if (this.data.playlessoninfo.status == 0) {
        Toast('课程未开课！', 'fail', 1000);
      }
      if (this.data.playlessoninfo.status == 2) {
        Toast('课程已结束！', 'fail', 1000);
      }
      return false;
    }
    wx.chooseImage({
      count: 9, // 默认9
      sizeType: ['compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function(res) {
        for (var i = 0; i < res.tempFilePaths.length; i++) {
          var size = (res.tempFiles[i].size / 1000).toFixed(2) + 'k'
          var addtimestamp = Math.round(Date.now() / 1000);
          let arrInfo = {
            id: 0,
            res_type: 2, //1代表语音
            res_path: res.tempFilePaths[i],
            size: size,
            upto: 1, //上传状态 0 代表未上传状态  // 或者上传失败 1 代表上传中 2代表上传成功
          }
          var lesson_res = that.data.lesson_res;
          var key = lesson_res.length;
          console.log('sendpic')
          lesson_res.push(arrInfo)
          console.log(that.data.lesson_res)
          lesson_res.forEach(item => {
            if (item.res_type === 1) {
              item.bl = false;
              item.new = true;
            }
          })
          that.setData({
            lesson_res: lesson_res
          })
          that.up_res(res.tempFilePaths[i], key, size, addtimestamp, 2)
        }
      }
    })
  },
  socketMessage: function(message) {
    console.log(message);
    var messageInfo = JSON.parse(message);
    var that = this;
    var commentlist = that.data.commentlist;
    //如果是进入房间消息
    if (messageInfo.sendMessage.type == 'addUser') {
      commentlist.push({
        userid: messageInfo.sendUser.id,
        nickname: messageInfo.sendUser.nickname,
        headurl: messageInfo.sendUser.headurl,
        msg: messageInfo.sendUser.nickname + '进入了课程！',
        types: 'addUser'
      })
      that.setData({
        commentlist: commentlist,
        roomNumber: messageInfo.sendMessage.roomNumber
      })
    }
    if (messageInfo.sendMessage.type == 'lesson_comment') { //如果是发布的评论信息
      commentlist.unshift({
        userid: messageInfo.sendUser.id,
        nickname: messageInfo.sendUser.nickname,
        headurl: messageInfo.sendUser.headurl,
        msg: messageInfo.sendMessage.msg,
        types: 'lesson_comment'
      })
      that.setData({
        commentlist: commentlist,
      })
    }
    //如果退出房间
    if (messageInfo.sendMessage.type == 'closeUser') {
      that.setData({
        roomNumber: messageInfo.sendMessage.roomNumber
      })
    }
  },
  previewImg(e) {
    console.log(e)
    let url = e.currentTarget.dataset.url;
    wx.previewImage({
      current: url, // 当前显示图片的http链接
      urls: [url] // 需要预览的图片http链接列表
    })
  }

})